#import memcache

from helpers import get_sorted_tuple as gst, safe_int
import sqlite3 as sqlite

#mc = memcache.Client(['127.0.0.1:11211'], debug=0)

class ItemsDB:
    def __init__(self, db_filename):
        self.conn = sqlite.connect(db_filename)
        self.cur = self.conn.cursor()
        
    def close(self):
        self.cur.close()
        
    def commit(self):
        self.conn.commit()
    
    def get_item_users(self, item):
    #    key = 'iu_%s' % item
    #    n = mc.get(key)
    #    if n == None:
        self.cur.execute("select n from items_n where item = ?", (item,))
        n = safe_int(self.cur.fetchone())
    #        mc.set(key, n, time=0)
        return n
    
    def get_item_to_item(self, item1, item2):
    #    key = 'i_to_i_%s-%s' % gst(item1, item2)
    #    n = mc.get(key)
    #    if n == None:
        self.cur.execute("select n from items where item1 = ? and item2 = ?", gst(item1, item2))
        n = safe_int(self.cur.fetchone())
    #        mc.set(key, n, time=0)
        return n
    
    def get_subscriptions(self, uid):
        self.cur.execute("select distinct(item) from subscriptions where uid = ?", (uid,))
        return [x for (x,) in self.cur.fetchall()]
    
    def get_shadow_items(self, items):
        _items = ', '.join(map(str, items))
        self.cur.execute("select item1 from items where item2 in (%s)" % (_items,))
        shadow = set([x for (x,) in self.cur.fetchall()])
    
        #print time.time()
    
        self.cur.execute("select item2 from items where item1 in (%s)" % (_items,))
        shadow.update([x for (x,) in self.cur.fetchall()])
    
        return list(shadow)
        
    def get_items1(self):
        self.cur.execute("select distinct item1 from items")
        return [x for (x,) in self.cur.fetchall()]
        
    def get_shadow_items_sort(self, items, limit=100):
        _items = ', '.join(map(str, items))
        sql1 = "select n, item2 from items where item1 in (%s) order by n desc limit (%s)" % (_items, limit)
        sql2 = "select n, item1 from items where item2 in (%s) order by n desc limit (%s)" % (_items, limit)
            
        self.cur.execute(sql1)
        shadow = [x for x in self.cur.fetchall()]
        
        self.cur.execute(sql2)
        shadow.extend([x for x in self.cur.fetchall()])
        
        return shadow
    
    def get_half_shadow_item(self, item):
        self.cur.execute("select item2 from items where item1 = (%s)" % (item,))
        return [x for (x,) in self.cur.fetchall()]

    def update_items(self, r, it1, it2):
        self.cur.execute("update items set n = n / ? where item1 = ? and item2 = ?", (float(r), it1, it2))

